import { MyVue } from '@/common/MyVue';
import { Component } from "vue-facing-decorator";
import Constant, { TopBar } from '@/constant/Constants';
import { UserInfo } from '@/model/UserInfo';
import { UserService } from '@/service/UserService';
import Util from '@/utils/Util';
import StringUtil from '@/utils/StringUtil';
import PostInfo from '@/model/PostInfo';
import { PostService } from '@/service/PostService';
import { PostRequest } from '@/protocol/request/PostRequest';
import LoggerUtil from '@/utils/LoggerUtil';
import User from '../tabbar/user/user';
@Component
export default class Blogger extends MyVue {
    cdnHost = Constant.cdnHost;
    recommendList = new Array<UserInfo.SimpleUser>();
    postList = new Array<PostInfo>();
    postMap = new Map<number, PostInfo>();
    showRecommend: boolean = false;
    selectIndex: number = 0;
    selectStatus: number = 0;
    user = new UserInfo.UserData();
    request: PostRequest.QueryList = new PostRequest.QueryList();
    translateX = {
        'transform': '',
        '-webkit-transform': '',
        '-moz-transform': ''
    };
    scrollTop: number = 0; // 用于吸顶处理
    stickyKey: number = 0; // 用于强制刷新 fui-sticky 组件

    /**
     * 重置吸顶状态，确保组件正确工作
     */
    resetStickyState() {
        // 通过改变 key 值强制重新渲染 fui-sticky 组件
        this.stickyKey++;
        this.$nextTick(() => {
            this.$forceUpdate();
        });
    }

    async onLoad(options: any) {

        const pages = getCurrentPages();  // 无需import
        const page = pages[pages.length - 1];
        let that = this;
        const eventChannel = (<any>page).getOpenerEventChannel();
        eventChannel.on('toUser', async (data: any) => {
            that.request.uid = data.userId;
            that.user.uid = data.userId;
            that.loadUser();
            await that.loadPost();
        })

    }

    async loadPost() {

        let recommendList = await UserService.queryRecommedList(this.request);
        Util.copyList(this.recommendList, recommendList, UserInfo.SimpleUser);
        this.setTabTranslateX();

        this.postList.length = 0;
        this.request.pageIndex = 1;
        await this.loadPostList();

        // 页面加载完成后，计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
        });
    }


    async onReachBottom() {
        this.request.pageIndex += 1;
        await this.loadPostList();

        // 分页加载后，无需重新计算吸顶触发点，保持当前吸顶状态
        console.log('分页加载完成，当前页:', this.request.pageIndex, '数据量:', this.postList.length);
    }

    toUser(e) {
        const uid = e.currentTarget.dataset.id;
        uni.navigateTo({
            url: "/pages/blogger/blogger", success: (res) => {
                res.eventChannel.emit('toUser', { userId: uid });
            }
        });

    }

    async loadUser() {
        let user = await UserService.getPublicData(this.user);
        Util.copy(this.user, user);
        uni.setNavigationBarTitle({ title: this.user.nick });
    }
    async loadPostList() {
        this.request.pageSize = 30;
        if (this.selectIndex == 0) {
            // 作品
            this.request.type = 0;
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.postId = this.postList.length > 0 ? this.postList[this.postList.length - 1].id : 0;
        } else if (this.selectIndex == 1) {
            // 收藏
            this.request.type = 3; // 收藏类型
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.postId = this.postList.length > 0 ? this.postList[this.postList.length - 1].lnkId : 0;
        } else if (this.selectIndex == 2) {
            // 喜欢
            this.request.type = 1; // 收藏类型
            let post = await PostService.queryUserList(this.request);
            Util.copyList(this.postList, post, PostInfo);
            this.request.postId = this.postList.length > 0 ? this.postList[this.postList.length - 1].lnkId : 0;
        }

        uni.setNavigationBarTitle({ title: this.user.nick });
        this.postMap.clear();
        this.postList.forEach(element => {
            this.postMap.set(element.id, element);
        });

    }

    truncate(str) {
        return Util.truncate(str, 10);
    }

    /**
     * 页面显示时重新计算吸顶触发点
     */
    async onReady() {
        await this.getTabOffsetTop();
    }

    /**
     * 推荐区显示/隐藏时重新计算吸顶触发点
     */
    onShowRecommend() {
        console.log("onShowRecommend")
        this.showRecommend = !this.showRecommend;

        // 推荐区变化后，重新计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
        });
    }
    setTabTranslateX() {
        Object.keys(this.translateX).forEach(key => {
            let val = this.translateX[key];
            this.translateX[key] = StringUtil.format('translateX({})', [this.selectIndex * 100 + '%']);
        })
    }
    async onTabSelect(e) {
        const targetIndex = parseInt(e.currentTarget.dataset.index);
        const targetId = parseInt(e.currentTarget.dataset.id);

        console.log('点击Tab:', targetIndex, 'ID:', targetId, '当前index:', this.selectIndex);

        if (this.selectIndex == targetIndex) {
            return;
        }

        // 简化状态管理，立即更新Tab状态
        this.selectStatus = targetId;
        this.selectIndex = targetIndex;
        this.setTabTranslateX();

        // 清空数据并重新加载
        this.postList.length = 0;
        this.request.pageIndex = 1;
        this.request.postId = 0; // 重置postId以确保加载新数据
        this.request.lnkId = 0; // 重置lnkId以确保加载新数据

        console.log('开始加载数据...');
        await this.loadPostList();
        console.log('数据加载完成，数据量:', this.postList.length);

        // 确保Tab切换后重新计算吸顶触发点
        this.$nextTick(async () => {
            await this.getTabOffsetTop();
        });

        // 简化吸顶处理，不使用复杂的锁定机制
        const hasContent = this.postList.length > 0;
    }
    generateId(itemId: any, index: any) {
        return itemId + Date.now();
    }


    toPost(e) {
        const postId = e.currentTarget.dataset.id;
        const lnkId = e.currentTarget.dataset.lnkId  // 如果没有lnkId，默认为0
        let type = this.dataType()
        uni.navigateTo({ url: "/pages/blogger/post?postId=" + postId + "&uid=" + this.request.uid + "&type=" + type + "&lnkId=" + lnkId });
    }

    dataType() {
        if (this.selectIndex == 0) {
            return 0; // 作品
        } else if (this.selectIndex == 1) {
            return 3; // 收藏
        } else if (this.selectIndex == 2) {
            return 1; // 喜欢
        }

    }

    /**
     * 精确的scroll监听，基于用户信息区域高度处理吸顶
     */
    onScroll(e: any) {
        this.scrollTop = e.detail.scrollTop;
        // 启用手动吸顶处理
        this.handleManualSticky(e.detail.scrollTop);
    }

    /**
     * 备选方案：手动吸顶处理，如果 fui-sticky 不稳定可启用
     */
    isTabSticky: boolean = false;
    tabOffsetTop: number = 0;
    tabContainerHeight: number = 80; // Tab容器的实际高度，用于占位

    /**
     * 获取Tab容器的offsetTop值和高度
     */
    async getTabOffsetTop() {
        return new Promise((resolve) => {
            // 延迟一点时间确保DOM完全渲染
            setTimeout(() => {
                // 获取Tab容器的实际高度
                uni.createSelectorQuery().in(this).select('.tab-container-wrapper').boundingClientRect((data: any) => {
                    if (data) {
                        this.tabContainerHeight = data.height || 80; // 获取Tab容器的实际高度
                        console.log('Tab容器高度:', this.tabContainerHeight, '完整信息:', data);
                    }
                }).exec();

                // 获取用户信息区域的高度作为吸顶触发点
                uni.createSelectorQuery().in(this).select('.fui-page__bd-user').boundingClientRect((data: any) => {
                    if (data) {
                        this.tabOffsetTop = data.height + 42.3 || 340; // 如果获取失败，使用默认值
                        console.log('用户信息区域高度:', this.tabOffsetTop);
                        resolve(this.tabOffsetTop);
                    } else {
                        this.tabOffsetTop = 340;
                        resolve(340);
                    }
                }).exec();
            }, 100);
        });
    }

    /**
     * 手动处理吸顶逻辑（备选方案）
     */
    handleManualSticky(scrollTop: number) {
        const shouldSticky = scrollTop >= this.tabOffsetTop;
        if (this.isTabSticky !== shouldSticky) {
            console.log('吸顶状态变化:', shouldSticky, 'Tab容器高度:', this.tabContainerHeight);
            this.isTabSticky = shouldSticky;
        }
    }

    onfollow() {
        let auth = UserService.isAuth();
        if (!auth) {
            return;
        }
        LoggerUtil.info("follow user: {}", this.user.uid);
        if (this.user.followed) {
            UserService.unfollow(this.user.uid);
            this.user.followed = false;
        } else {
            UserService.follow(this.user.uid);
            this.user.followed = true;
        }
    }

    onFollowRecommend(e: any) {
        LoggerUtil.info("rfollow user: {}", e.currentTarget.dataset.id);
        let auth = UserService.isAuth();
        if (!auth) {
            return;
        }
        const uid = e.currentTarget.dataset.id;
        UserService.follow(uid);
        //将这个用户从follow 列表中移除
        this.recommendList = this.recommendList.filter(item => item.uid !== uid);
    }

    deleteRecommendUser(e: any) {
        LoggerUtil.info("delete recommend user: {}", e.currentTarget.dataset.index);
        let index = e.currentTarget.dataset.index;
        if (index < 0 || index >= this.recommendList.length) {
            LoggerUtil.error("Index out of bounds for recommend list");
            return;
        }
        this.recommendList.splice(index, 1); // 从推荐列表中删除该用户
    }




}